package com.yj.cloudnote.common.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

public class TokenUtil {

    //密匙
    private static final String authorize = "Hello0216SuperMan";

    /**
     * @Author: jy
     * @Description: 生成token
     * @Params: String poyload
     * @Date: 11:11 2018/4/10
     */
    public static String createToken(String poyload) {
        //
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        // 密匙
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(authorize);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes,signatureAlgorithm.getJcaName());
        // create (没有添加head的信息，因为自己会添加默认的值，此处省略)
        JwtBuilder builder = Jwts.builder()
                .setPayload(poyload)
                .signWith(signatureAlgorithm,signingKey);
        return builder.compact();
    }

    /**
     * @Author: jy
     * @Description: 根据传入参数token判断是否合法的token;是：true
     * @Date: 11:36 2018/4/10
     */
    public static boolean authToken(String token) {
        if(token.split("\\.").length == 3) {
//            String head = token.split("\\.")[0];    //头部
//            String poyload = token.split("\\.")[1]; //负荷
            String sign = token.split("\\.")[2];    //签名
            Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(authorize))
                    .parseClaimsJws(token).getBody();     //负荷信息
            String sign_auth = createToken(JSONObject.toJSONString(claims)).split("\\.")[2];
            if(sign_auth.equals(sign)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @Author: jy
     * @Description: 判断token是都过期；过期：true
     * @Date: 14:19 2018/4/10
     */
    public static Boolean isOverdue(String token){
        Claims claims = TokenUtil.getTokenPoyload(token);
        Long nowMillis = System.currentTimeMillis();
        Long expMillos = Long.parseLong(claims.get("expMillis").toString());
        if (nowMillis >= expMillos) {
            return true;
        }
        return false;
    }

    /**
     * @Author: jy
     * @Description: 获取负荷的信息
     * @Date: 11:52 2018/4/10
     */
    public static Claims getTokenPoyload(String token) {
        if (token.split("\\.").length == 3) {
            Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(authorize))
                    .parseClaimsJws(token).getBody();
            return claims;
        }
        return null;
    }

}
